<template>
  <div class="app-container">
    <!-- 返回按钮和项目名称 -->
    <PageHeader back-text="返回审批列表" back-type="back" :title="auditInfo.proName || '加载中...'" />

    <!-- 项目详情卡片 -->
    <ProjectDetail :project-info="auditInfo" :loading="loading" :show-commit-status="true" :show-flow-status="true" />

    <!-- 项目计划列表卡片 -->
    <el-card class="mb-6 box-card" v-loading="loading">
      <!-- 搜索栏 -->
      <div class="search-section mb-4">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
          <el-form-item label="工作流程" prop="flowName">
            <el-input v-model="queryParams.flowName" placeholder="请输入工作流程" clearable @keyup.enter="handleQuery" style="width: 240px" />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              style="width: 300px"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
          <!-- 排序功能 -->
          <el-form-item style="margin-left: auto">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-select v-model="sortField" placeholder="请选择排序字段" style="width: 170px" clearable @change="handleSortChange">
                <el-option label="工作流程" value="flowName" />
                <el-option label="总绩效" value="totalPerf" />
                <el-option label="创建时间" value="createTime" />
              </el-select>
              <el-button
                v-if="sortField"
                :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'"
                @click="toggleSortOrder"
                type="info"
                plain
                size="small"
                :title="sortOrder === 'asc' ? '当前为正序，点击切换为逆序' : '当前为逆序，点击切换为正序'"
              >
                {{ sortOrder === 'asc' ? '正序' : '逆序' }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #header>
        <div class="card-header">
          <span class="title">项目计划列表</span>
          <ProjectStatusDisplay label="当前项目计划状态" :status-options="approval_commit_status" :status-value="auditInfo.flowStatus" />
        </div>
      </template>

      <div class="flow-container">
        <div class="scroll-tip-container">
          <div class="scroll-tip">
            <el-icon class="tip-icon">
              <ArrowLeft />
            </el-icon>
            <span class="tip-text">左右滑动查看更多信息</span>
            <el-icon class="tip-icon">
              <ArrowRight />
            </el-icon>
          </div>
        </div>
        <el-table :data="flowList" border style="width: 100%">
          <!-- 序号 -->
          <el-table-column label="序号" align="center" width="80" fixed="left">
            <template #default="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工作流程" prop="flowName" width="200" align="center" fixed="left" show-overflow-tooltip />
          <el-table-column label="工作内容" prop="workContent" width="300" fixed="left" show-overflow-tooltip />
          <el-table-column label="计划开始时间" prop="planStartDate" width="200" align="center">
            <template #default="scope">
              {{ scope.row.planStartDate ? parseTime(scope.row.planStartDate, '{y}-{m}-{d}') : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="计划完成时间" prop="planEndDate" width="200" align="center">
            <template #default="scope">
              {{ scope.row.planEndDate ? parseTime(scope.row.planEndDate, '{y}-{m}-{d}') : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="计划占比(%)" prop="planRatio" width="200" align="center">
            <template #default="scope"> {{ scope.row.planRatio ? Number(scope.row.planRatio).toFixed(2) : '0.00' }}% </template>
          </el-table-column>
          <el-table-column label="人员(人)" prop="persons" width="200" align="center">
            <template #default="scope"> {{ scope.row.persons || 0 }}人 </template>
          </el-table-column>
          <el-table-column label="工天(天)" prop="workDays" width="200" align="center">
            <template #default="scope"> {{ scope.row.workDays || 0 }}天 </template>
          </el-table-column>
          <el-table-column label="总人工天(天)" prop="totalPd" width="200" align="center">
            <template #default="scope">
              <span style="color: #f56c6c; font-weight: bold">{{ scope.row.totalPd || 0 }}天</span>
            </template>
          </el-table-column>
          <el-table-column v-if="hasPerDataQueryPermission" label="单位绩效(元/人/天)" prop="unitPerf" width="200" align="center">
            <template #default="scope"> {{ formatAmount(scope.row.unitPerf) }}元 </template>
          </el-table-column>
          <el-table-column v-if="hasPerDataQueryPermission" label="计划绩效(元)" prop="planPerf" width="200" align="center">
            <template #default="scope">
              <span style="color: #f56c6c; font-weight: bold">{{ formatAmount(scope.row.planPerf) }}元</span>
            </template>
          </el-table-column>
          <el-table-column v-if="hasPerDataQueryPermission" label="差旅费（元）" prop="difference" width="200" align="center">
            <template #default="scope"> {{ formatAmount(scope.row.difference) }}元 </template>
          </el-table-column>
          <el-table-column v-if="hasPerDataQueryPermission" label="办公费（元）" prop="officeFee" width="200" align="center">
            <template #default="scope"> {{ formatAmount(scope.row.officeFee) }}元 </template>
          </el-table-column>
          <el-table-column v-if="hasPerDataQueryPermission" label="业务费用（元）" prop="businessFee" width="200" align="center">
            <template #default="scope"> {{ formatAmount(scope.row.businessFee) }}元 </template>
          </el-table-column>
          <el-table-column v-if="hasPerDataQueryPermission" label="外协费用（元）" prop="outFee" width="200" align="center">
            <template #default="scope"> {{ formatAmount(scope.row.outFee) }}元 </template>
          </el-table-column>
          <el-table-column v-if="hasPerDataQueryPermission" label="总绩效(元)" prop="totalPerf" width="200" align="center">
            <template #default="scope">
              <span style="color: #f56c6c; font-weight: bold">{{ formatAmount(scope.row.totalPerf) }}元</span>
            </template>
          </el-table-column>
          <el-table-column label="成本说明" prop="costDescription" width="300" show-overflow-tooltip />
          <el-table-column label="备注" prop="remark" width="300" show-overflow-tooltip />
          <el-table-column label="创建人" prop="createBy" width="150" align="center" />
          <el-table-column label="创建时间" prop="createTime" width="150" align="center">
            <template #default="scope">
              {{ scope.row.createTime ? parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[100, 150, 200, 250]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核操作组件 -->
    <AuditAction v-if="checkContractStatus(auditInfo.proStatus)" :loading="auditLoading" @audit="handleAuditAction" />

    <!-- 审核流程组件 -->
    <ApprovalFlowDisplay
      :business-type="'PROJECT-SPLIT-FLOW'"
      :business-id="String(route.params.proId)"
      title="审核流程"
      :auto-load="true"
      :show-collapse="true"
      @data-loaded="handleApprovalDataLoaded"
      @error="handleApprovalError"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getProInfo } from '@/api/project/init/proInfo';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import { listProFlow } from '@/api/project/plan/flow';
import type { ProFlowQuery } from '@/api/project/plan/flow/types';
import { audit } from '@/api/other/approval/index';
import ProjectDetail from '@/views/project/components/ProjectDetail.vue';
import ApprovalFlowDisplay from '@/components/ApprovalFlowDisplay/index.vue';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import AuditAction from '@/components/AuditAction/index.vue';
import ProjectStatusDisplay from '@/views/project/components/ProjectStatusDisplay.vue';
import { checkContractStatus, checkPermi } from '@/utils/permission';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

// 获取字典数据
const { proxy } = getCurrentInstance() as any;
const { approval_commit_status } = toRefs<any>(proxy?.useDict('approval_commit_status'));

// 项目信息
const auditInfo = ref<Partial<ProInfoVO>>({});
const projectLoading = ref(false);

// 数据状态
const loading = ref(false);
const auditLoading = ref(false);
const flowList = ref<any[]>([]);

// 分页参数
const queryParams = ref<ProFlowQuery>({
  pageNum: 1,
  pageSize: 100,
  proId: Number(route.params.proId),
  flowName: undefined,
  params: {}
});

// 总条数
const total = ref(0);

// 日期范围
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

// 排序字段
const sortField = ref('');
// 排序顺序
const sortOrder = ref('asc');

// 是否有绩效数据查询权限（涉及金额）
const hasPerDataQueryPermission = computed(() => checkPermi(['project:perdata:query']));

/**
 * 处理审核数据加载完成事件
 */
const handleApprovalDataLoaded = (data: any[]) => {
  console.log('审核流程数据加载完成:', data);
};

/**
 * 处理审核错误事件
 */
const handleApprovalError = (error: any) => {
  console.error('审核流程加载失败:', error);
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getFlowListData();
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  sortField.value = '';
  sortOrder.value = 'asc';
  queryParams.value = {
    pageNum: 1,
    pageSize: 100,
    proId: Number(route.params.proId),
    flowName: undefined,
    params: {}
  };
  handleQuery();
};

/**
 * 处理分页变化
 */
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  getFlowListData();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getFlowListData();
};

/**
 * 处理审核操作
 */
const handleAuditAction = async (auditData: { status: string; idea: string }) => {
  try {
    auditLoading.value = true;
    await audit({
      businessId: route.params.proId as string,
      businessType: 'PROJECT-SPLIT-FLOW',
      status: auditData.status,
      idea: auditData.idea
    });

    const message = auditData.status === '1' ? '审核通过成功' : '审核不通过操作完成';
    ElMessage.success(message);
    setTimeout(() => {
      router.push('/project/plan/flowAudit');
    }, 1500);
  } catch (error) {
    console.error('审核操作失败:', error);
    ElMessage.error((error as any)?.message || '审核操作失败');
  } finally {
    auditLoading.value = false;
  }
};

/**
 * 格式化金额
 */
const formatAmount = (amount: any) => {
  if (amount === null || amount === undefined || amount === '') return '0.00';
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

/**
 * 处理排序变化
 */
const handleSortChange = () => {
  // 如果选择了排序字段但没有选择排序顺序，则设置默认值
  if (sortField.value && !sortOrder.value) {
    sortOrder.value = 'asc';
  }
  // 刷新流程列表
  getFlowListData();
};

/**
 * 切换排序顺序
 */
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  // 刷新流程列表
  getFlowListData();
};

/**
 * 获取项目信息
 */
const getProjectDetail = async () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }

  try {
    projectLoading.value = true;
    const res = await getProInfo(proId);
    auditInfo.value = res.data || {};
  } catch (error) {
    console.error('获取项目信息失败:', error);
    ElMessage.error('获取项目信息失败');
  } finally {
    projectLoading.value = false;
  }
};

/**
 * 获取流程列表数据
 */
const getFlowListData = async () => {
  try {
    loading.value = true;
    const params = { ...queryParams.value };
    // 使用addDateRange工具方法处理创建时间范围
    proxy?.addDateRange(params, dateRange.value, 'CreateTime');
    // 处理排序参数
    if (sortField.value && sortOrder.value) {
      (params as any).orderByColumn = sortField.value;
      (params as any).isAsc = sortOrder.value;
    }

    const res = await listProFlow(params);
    flowList.value = res.rows || [];
    total.value = res.total;
  } catch (error) {
    console.error('获取流程列表失败:', error);
    ElMessage.error('获取流程列表失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getProjectDetail();
  getFlowListData();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.box-card {
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 16px;
    font-weight: bold;
  }
}

.search-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #dee2e6;
}

.search-form {
  margin: 0;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.search-form .el-form-item:last-child {
  margin-right: 0;
}

.flow-container {
  position: relative;
  margin-top: 20px;

  .scroll-tip-container {
    position: absolute;
    left: 0;
    bottom: -45px;
    flex-shrink: 0;
  }

  .scroll-tip {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 12px;
    color: #909399;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    padding: 6px 12px;
    border-radius: 4px;
    display: inline-flex;
  }

  .tip-icon {
    font-size: 14px;
    color: #909399;
  }

  .tip-text {
    font-size: 12px;
    color: #909399;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.mb-4 {
  margin-bottom: 16px;
}

.mb-6 {
  margin-bottom: 24px;
}

:deep(.el-table) {
  .el-table__cell {
    vertical-align: middle;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 8px;
  }
}
</style>
